<template>
  <div>
    <el-card shadow="never" :body-style="{ padding: '0px' }">
      <div slot="header">
        <el-row :gutter="10" type="flex" justify="start">
          <el-col :span="3">
            <el-form :model='dropList'>
          <el-select v-model="dropList.id" placeholder="请选择" clearable
          @change="selectTrigger(dropList.id)">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.claName"
              :value="item.id">
            </el-option>
          </el-select>
            </el-form>
          </el-col>
          <el-col :span="6">
             <el-form :model='content'> 
               <el-form-item prop='name' label=''> 
                <el-input v-model='content.name' placeholder="教师昵称" clearable></el-input>
               </el-form-item> 
            </el-form> 
          </el-col>
          <el-col :span="35">
            <el-button type="primary" icon="el-icon-search" @click="query()">查询</el-button>
          </el-col>
          <!-- <el-col :span="40">
            <el-button type="primary" icon="el-icon-plus" @click="addExams()">添加考试</el-button>
           </el-col> -->
        </el-row>
      </div>
      <el-table :data="pager.content" style="width: 100%" stripe highlight-current-row v-loading="$store.state.loading" @selection-change="onSelectionChange"
      :default-sort= "{prop:'date',order:'descending'}" >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column prop="name" label="账号名称" ></el-table-column>
        <el-table-column prop="nickname" label="昵称" ></el-table-column>
        <el-table-column prop="age" label="年龄" sortable ></el-table-column>
        <el-table-column prop="email" label="邮箱" ></el-table-column>
        <el-table-column label="修改日期" sortable  prop="updateDate" align="center">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left:5px">{{ scope.row.updateDate | moment('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" sortable  prop="creationDate" align="center">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left:5px">{{ scope.row.creationDate | moment('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120" prop="state" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state == 'true'" :type="'success'">已启用</el-tag>
            <el-tag v-if="scope.row.state == 'false'" :type="'danger'">已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="summary" label="备注" width="270" align="center"></el-table-column>
        <el-table-column label="操作" width="310" align="center">
          <template slot-scope="scope">
            <el-button size='medium' type="primary"  @click='addCla(scope.$index, scope.row)'>关联班级</el-button>
            <el-button size='medium' type="warning" @click='handleEditRow(scope.$index, scope.row)'>编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" 
          :page-size="pager.pageable.pageSize" 
          :total="pager.totalElements" 
          class="pagination text-right" 
          :page-sizes="$store.state.paginationPageSizes" 
          :layout="$store.state.paginationLayout">
      </el-pagination>
    </el-card>

    <el-dialog title="编辑教师信息" :visible.sync="dialogVisible">
      <el-form :label-position="'right'" label-width="80px" ref="userForm" :model="userForm" :rules="rules_update">
        <el-form-item label="教师昵称" prop="name">
          <el-input placeholder="请输入昵称" v-model="userForm.nickname" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state11">
          <el-switch v-model="userForm.state" active-text="启用" inactive-text="禁用" active-value="true" inactive-value="false"></el-switch>
        </el-form-item>
        <!-- <el-form-item label="班级">
          <el-select v-if="userForm.cla" v-model="userForm.cla.id" placeholder="请选择">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.claName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="备注">
          <el-input type='textarea' v-model="userForm.summary" auto-complete='off' rows="4" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('userForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title='提示' width='25%' :visible.sync='deleteVisible'>
            <span>确定执行数据删除操作 ? </span>
            <span slot='footer'>
                <el-button type='text' @click='deleteVisible=false'>取消</el-button>
                <el-button type='primary' @click='handleDeleteConfirm'>确定</el-button>
            </span>
    </el-dialog>


    <el-dialog title='班级'  :visible.sync='menuVisible' width='40%'>
            <el-transfer v-model='currentCla' :data='allRoles' :props="{key:'id',label:'claName'}" :titles="['未分配班级', '已分配班级']" filterable 
            style="text-align: left; display: inline-block;margin-left:90px;">
            </el-transfer>
            <div slot='footer'>
                <el-button @click='menuVisible=false'>取消</el-button>
                <el-button type='primary' @click='handleMenuSubmit'>确定</el-button>
            </div>
  </el-dialog>

  </div>

  
</template>
<style>
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
<script>
export default {
  name: "user",
  data() {
    var validateName = (rule,value,callback) => {
      if(typeof(value) == "undefined" || value == ""){
          callback(new Error('请输入角色名称'));
        }else{
            this.$http.get("/api/accounts/isExit",{params:{'name':value}}).then(res => {
          if(res.data == true){
              callback();
          }else{
              callback(new Error('该角色名称已经存在'));
          }
        })
        }
    };
    var validateUpdateName = (rule,value,callback) => {
      if(typeof(value) == "undefined" || value == "")
      {
        callback(new Error('请输入角色名称'));
      }else{
        if(value == this.roleName){
          callback();
        }else{
          this.$http.get("/api/accounts/isExit",{params:{'name':value}}).then(res => {
          if(res.data == true){
              callback();
          }else{
              callback(new Error('该角色名称已经存在'));
          }
        })
        }
      }
    }
    return {
      options2: new Object(),
      options1: new Object(),
      dropList: new Object(),
      options:new Object(),
      total:'',
      size: '',
      content : new Object(),
      currentData: new Object(),
      userForm : {
        id:"",
        name:"",
        state:"",
        summary:"",
        created:{
          id:""
        },
        exams:[{id:""}],
        cla:{
          id:"",
          claName:""
        }
      },
      userForm_add : {
        name:"",
        state:"",
        summary:"",
        created:{
          id:""
        }},
      addExamsVisible:false,
      deleteVisible: false,
      dialogVisible: false,
      dialogAddVisible: false,
      menuVisible: false,
      currentData:new Object() ,
      currentDataCla: new Object(),
      currentCla: new Array(),
      currentMenus : new Array() ,
      allRoles : new Array() ,
      tabledata : new Array() ,
      state: null,
      dateRange: null,
      roleName:"",
      userId : this.$store.state.userId ,
      selectedRows: [],
      bucketName: "public",
      pager: {pageable:[], totalElements: 0, content: [] },
      rules_add: {name:[{required:true,validator: validateName,trigger:'blur'}]},
      rules_update: {name:[{required:true,validator:validateUpdateName,trigger:'blur'}],
                      }
    };
  },
  mounted() {
    this.query();
    this.getDropList();
  },
  methods: {
    getDropList() {
      this.$http.get("/api/cla/noPage").then(res => {
        this.options = res.data;
      })
    },
    query() {
      if(this.content.name !== "" && typeof(this.content.name) != "undefined"){
        this.$http.get("/api/accounts/teachers/nickname",{params:{"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize,"nickname":this.content.name}}).then(res => {
        this.pager = res.data;
        });
      }else if(!this.content.name && !this.dropList.id) {
        this.$http.get("/api/accounts/teachers/",{params:{"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize}}).then(res => {
        this.pager = res.data;
        });
      }
      else{
        this.$http.get("/api/accounts/teachers/class",{params:{"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize,"classId":this.dropList.id}}).then
        (res=> {
          this.pager = res.data;
        })
      }
    },
    handleEditRow(index,row) {
      this.options1 = this.options;
      this.roleName = row.name;
      this.dialogVisible = true;
      this.userForm = Object.assign({},row) ;
    },
    onSelectionChange(rows) {
      this.selectedRows = rows.map(item => item.id);
    },
    remove(index,row) {
      this.deleteVisible = true ;
      this.currentData = row;
    },
    onRemoveFile(file) {
      this.$http.delete(`/oss/remove/${this.bucketName}/${file.response}`);
    },
    handleSizeChange(val) {
        this.$http.get("/api/accounts/teachers",{params:{"size":val,"pageable":'1'}}).then(res => {
        this.pager = res.data;
      });
      },
    handleCurrentChange(val) {
        this.$http.get("/api/accounts/teachers",{params:{"page":val-1,"size":this.pager.pageable.pageSize,"pageable":'1'},}).then(res => {
        this.pager = res.data;
        });
      },
    onSubmit(userForm)
    {
      this.$refs[userForm].validate((valid) => {
        if(valid)
        {
          if(this.userForm.id){
            this.$http.put("/api/accounts/"+this.userForm.id,this.userForm).then(res => {
              if(res.status == 200)
              {
                this.userForm = res.data;
                this.$notify({type:'success',title:'成功',message:'修改成功'}) ;
                this.dialogVisible = false;
                this.userForm = {id:"",name:"",state:"",summary:"",created:{id:""},cla:{
          id:"",
          claName:""
        }};
                this.query();
              }
            })
          }else{
            this.userForm_add.created.id = this.$store.state.userId;
          this.$http.post("/api/accounts/",this.userForm_add).then(res => {
            if(res.status == 200)
            {
              this.$notify({type:'success',title:'成功',message:'添加成功'}) ;
              this.dialogAddVisible = false;
              this.userForm_add = {name:"",state:"",summary:"",created:{id:""}};
              this.query();
            }
          })
          }
        }
      })
    },
    handleDeleteConfirm(){
      this.$http.delete("/api/cla/"+this.currentData.id).then(res => {
        if(res.status == 204)
        {
          this.deleteVisible = false;
          this.currentData = {};
          this.query();
        }
      })
    },
    addCla(index,row){
      this.currentDataCla = row ;
      this.$http.get("/api/cla/noPage").then(res => {
        this.allRoles = res.data;
        let foo = Object.assign([],this.currentDataCla.cla) ;
        this.currentCla = foo && foo.length>0 ? foo.map(x=>x.id) : new Array() ;
        this.menuVisible = true ;
      }).catch(error=>console.error(error))
    },
  selectTrigger(val) {
        this.query();
    },
  addExams(){
    if(this.selectedRows.length == 0)
    {
      this.$notify({type:'error',title:'提示',message:'请选择要添加考试的学生'}) ;
    }else{
      this.addExamsVisible = true;
    }
  },
  handleMenuSubmit() {
                let o = Object.assign([],this.currentCla) .map(x=>{ return { id : x }; });
                let i = this.tabledata.findIndex( x=> x.id==this.currentDataCla.id ) ;

                this.$http.put("/api/accounts/"+this.currentDataCla.id+"/cla", o)
                    .then(res=>{
                        this.currentDataCla = res.data ;
                        this.tabledata.splice( i , 1 , this.currentDataCla) ;
                        this.menuVisible = false ;
                        this.query();
                        this.$notify({type:'success',title:'成功',message:'关联班级成功'}) ;
                    })
                    .catch(error=>console.error(error))
                ;
            } ,
  }
};
</script>
<style scope>
  .el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label {
      font-size: 12px;
  }
</style>